﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.MacroEngines;
using System.Xml;
namespace DigibizAdvancedMediaPicker.RazorModel
{

    public class Model : DynamicXml
    {
        public Model(string xml) : base(xml) { }
        public string CropUrl(string cropName)
        {
            var crop = this.XPath(string.Format("//crop[@name='{0}']", cropName));
            if (crop != null)
            {
                var firstElement = crop.BaseElement.Elements().ToList().FirstOrDefault();
                if (firstElement != null)
                {
                    var attr = firstElement.Attributes().Where(item => item.Name == "url").FirstOrDefault();
                    if (attr != null)
                    {
                        return attr.Value.Replace(" ", "%20");
                    }
                }
            }
            return string.Empty;
        }
        public dynamic Crop(string cropName)
        {
            var crop = new DynamicXml(this.XPath(string.Format("//crop[@name='{0}']", cropName)).BaseElement.Elements().FirstOrDefault());
            if (crop != null)
            {
                return crop;
            }
            return new DynamicNull();
        }
        public dynamic Image()
        {
            var image = new DynamicXml(this.BaseElement.Elements().FirstOrDefault().Descendants().FirstOrDefault());
            if (image != null)
            {
                return image;
            }
            return new DynamicNull();
        }

        public int Count()
        {
            var elements = this.XPath("//Image").BaseElement.Elements();
            if (elements != null) return elements.Count();
            return 0;
        }
    }
}
